package com.example.initializr.pj.datasource;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class jdvctest {
    @Autowired
   private DataSource dataSource;
@Test
    public  void saveTest() throws SQLException {
//1.建立连接
    Connection conn = dataSource.getConnection();
    //2.创建 Statement
    String sql = "select * "
            + " from rest_order";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    //3.发送 sql(发送到数据库)
    //  pstmt.setInt(1,2);
    boolean flag = pstmt.execute();
    //4.处理结果
    ResultSet rs = null;
    if (flag) {//true 表示查询,有结果集
        //获取结果集(二维表结构)
        rs = pstmt.getResultSet();
        List<Map<String, Object>> list = new ArrayList<>();
        while (rs.next()) {//一行记录应为一个 map 对象 (行映射)
            //构建 map，用于存储当前行记录
            Map<String, Object> map = new HashMap();
            //将取出类的数据存储到 map (key 为字段名,值为字段 value)
            map.put("id", rs.getInt("id"));
         //   map.put("title", rs.getString("title"));
//            map.put("content", rs.getString("content"));
//            map.put("status", rs.getString("status"));
//            map.put("type", rs.getString("type"));
//            map.put("createdTime",
//                    rs.getTimestamp("createdTime"));
            //...
            //将每行记录对应的 map 对象存储到 list 集合
            System.out.println(map);
            list.add(map);
        }
    }
    //5.释放资源
    rs.close();
    pstmt.close();
    conn.close();

}
}


